<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 存储副作用函数的桶
      const bucket = new WeakMap()
      let activeEffect

      // 原始数据
      const data = {
        text: 'hello world',
      }

      const obj = new Proxy(data, {
        get(target, key) {
          if (!activeEffect) return target[key]
          let depsMap = bucket.get(target)
          if (!depsMap) {
            bucket.set(target, (depsMap = new Map()))
          }

          let deps = depsMap.get(key)
          if (!deps) {
            depsMap.set(key, (deps = new Set()))
          }
          deps.add(activeEffect)

          return target[key]
        },

        set(target, key, newVal) {
          // 设置属性值
          target[key] = newVal

          const depsMap = bucket.get(target)
          if (!depsMap) return

          const effects = depsMap.get(key)

          effects && effects.forEach((fn) => fn())

          return true
        },
      })

      // 副作用函数
      function effect(fn) {
        activeEffect = fn
        fn()
      }

      effect(() => {
        console.log('ssss')
        document.body.innerText = obj.text
      })

      setTimeout(() => {
        obj.text = 'hello vue3'
      }, 1000)
    </script>
  </body>
</html>
